package cc.sunni.article.service.impl;

import cc.sunni.api.controller.user.UserControllerApi;
import cc.sunni.api.utils.PageUtils;
import cc.sunni.article.service.ArticlePortalService;
import cc.sunni.article.service.ArticleService;
import cc.sunni.common.Constant;
import cc.sunni.common.enums.ArticleReviewStatus;
import cc.sunni.common.enums.YesOrNo;
import cc.sunni.common.utils.R;
import cc.sunni.common.utils.RedisOperator;
import cc.sunni.pojo.Article;
import cc.sunni.pojo.vo.AppUserVO;
import cc.sunni.pojo.vo.ArticleDetailVO;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author jl
 * @since 2021/2/28 21:59
 */
@Service
public class ArticlePortalServiceImpl implements ArticlePortalService {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserControllerApi userControllerApi;
    @Autowired
    private RedisOperator redis;

    @Override
    public PageUtils queryIndexArticleList(String keyword, Integer category, Integer page, Integer pageSize) {
        IPage<Article> pages = articleService.page(
                new Page<>(page, pageSize),
                // 拼接查询条件
                new LambdaQueryWrapper<Article>().orderByDesc(Article::getPublishTime)
                        .eq(Article::getIsAppoint, YesOrNo.NO.type)
                        .eq(Article::getIsDelete, YesOrNo.NO.type)
                        .eq(Article::getArticleStatus, ArticleReviewStatus.SUCCESS.type)
                        .eq(category != null, Article::getCategoryId, category)
                        .like(StrUtil.isNotBlank(keyword), Article::getTitle, keyword)
        );
        return new PageUtils(pages);
    }

    @Override
    public List<Article> queryHotList() {
        return articleService.list(new LambdaQueryWrapper<Article>()
                .orderByDesc(Article::getPublishTime)
                .eq(Article::getIsAppoint, YesOrNo.NO.type)
                .eq(Article::getIsDelete, YesOrNo.NO.type)
                .eq(Article::getArticleStatus, ArticleReviewStatus.SUCCESS.type)
                .last("limit 5"));
    }

    @Override
    public PageUtils queryArticleListOfWriter(String writerId, Integer page, Integer pageSize) {
        IPage<Article> pages = articleService.page(
                new Page<>(page, pageSize),
                // 拼接查询条件
                new LambdaQueryWrapper<Article>().orderByDesc(Article::getPublishTime)
                        .eq(Article::getIsAppoint, YesOrNo.NO.type)
                        .eq(Article::getIsDelete, YesOrNo.NO.type)
                        .eq(Article::getArticleStatus, ArticleReviewStatus.SUCCESS.type)
                        .eq(Article::getPublishUserId,writerId)
        );
        return new PageUtils(pages);
    }

    @Override
    public PageUtils queryGoodArticleListOfWriter(String writerId) {
        IPage<Article> pages = articleService.page(
                new Page<>(1, 5),
                // 拼接查询条件
                new LambdaQueryWrapper<Article>().orderByDesc(Article::getPublishTime)
                        .eq(Article::getIsAppoint, YesOrNo.NO.type)
                        .eq(Article::getIsDelete, YesOrNo.NO.type)
                        .eq(Article::getArticleStatus, ArticleReviewStatus.SUCCESS.type)
                        .eq(Article::getPublishUserId,writerId)
        );
        return new PageUtils(pages);
    }

    @Override
    public ArticleDetailVO queryDetail(String articleId) {
        Article result = articleService.getById(articleId);
        ArticleDetailVO detailVO = new ArticleDetailVO();
        BeanUtils.copyProperties(result, detailVO);
        detailVO.setCover(result.getArticleCover());

        Set<String> idSet = new HashSet<>();
        idSet.add(detailVO.getPublishUserId());
        List<AppUserVO> publisherList = getPublisherList(idSet);
        if (CollectionUtil.isNotEmpty(publisherList)) {
            detailVO.setPublishUserName(publisherList.get(0).getNickname());
        }
        detailVO.setReadCounts(getCountsFromRedis(Constant.REDIS_ARTICLE_READ_COUNTS + ":" + articleId));
        return detailVO;
    }

    // 发起远程调用，获得用户的基本信息
    private List<AppUserVO> getPublisherList(Set<String> idSet) {
        R bodyResult = userControllerApi.queryByIds(JSONUtil.toJsonStr(idSet));
        List<AppUserVO> publisherList;
        if ((Integer) bodyResult.get("status") == 200) {
            String userJson = JSONUtil.toJsonStr(bodyResult.get("data"));
            publisherList = JSONUtil.toList(userJson, AppUserVO.class);
        } else {
            publisherList = new ArrayList<>();
        }
        return publisherList;
    }

    public Integer getCountsFromRedis(String key) {
        String countsStr = redis.get(key);
        if (StringUtils.isBlank(countsStr)) {
            countsStr = "0";
        }
        return Integer.valueOf(countsStr);
    }

}
